﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;

namespace KaiXin.BLL
{
    public class Common
    {

        const string LOGIN_URL = "http://www.kaixin001.com/login/login.php?";

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="email"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static bool Login(string email, string pwd)
        {
            WebHelper wh = new WebHelper(email);
            HtmlWeb hw = wh.GetHtmlWeb();
            HtmlDocument doc = hw.Load(LOGIN_URL + string.Format("email={0}&password={1}", email, pwd), "post");
            string title = doc.DocumentNode.SelectSingleNode("/html[1]/head[1]/title[1]").InnerText;
            if (title == null)
            {
                //被开心网防外挂程序屏蔽了该账号
                title = "挂罗";
            }
            return title.Trim() == "我的首页 - 开心网";
        }
        /// <summary>
        /// 判断是否已经登录开心网
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static bool IsLogin(HtmlDocument doc)
        {
            return doc.DocumentNode.SelectSingleNode("/html[1]/head[1]/title[1]").InnerText.Trim() != "登录 - 开心网";
        }
        /// <summary>
        /// 返回页数
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static int GetPageCount(HtmlDocument html)
        {
            HtmlNodeCollection nc = html.DocumentNode.SelectNodes("//a[@class='fy']");
            if (nc != null)
            {
                foreach (var item in nc)
                {
                    if (item.InnerText.Trim() == "末页")
                    {
                        string xp = item.Attributes["href"].XPath;
                        int s = item.Attributes["href"].Value.IndexOf("start");
                        string start = item.Attributes["href"].Value.Substring(s + 6);
                        return int.Parse(start) / 20 + 1;
                    }
                }
            }

            return 1;
        }
    }
}
